package com.example.tool.web.zop;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.tool.bean.ZopDO;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryResult;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryUtil;
import com.example.tool.zop.CallFun;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.example.tool.util.DateUtil.convertTimestampToDateTime;
import static com.example.tool.util.ExportUtil.writeExcel;

@Slf4j
@RestController
//@CrossOrigin(origins = "*")
@RequestMapping("/tool/zop")
public class ZopController {
    @RequestMapping("/wayBillTracksQuery")
    @ResponseBody
    public Object wayBillTracksQuery(@RequestParam(name = "billCodes") String billCodes) {
        return CallFun.wayBillTracksQuery(billCodes);
    }


    /**
     * @param file
     * @param response
     */

    @PostMapping("/getLogisticsTrack")
    public void getLogisticsTrack(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        try {
            List<ZopDO> dataList = EasyExcel.read(file.getInputStream()).sheet().head(ZopDO.class).doReadSync();
            dataList.forEach(e -> {
                JSONObject result = CallFun.wayBillTrackQuery(e.getBillCode());
                Boolean status = result.getBoolean("status");
                JSONArray data = result.getJSONArray("result");
                if (status && !data.isEmpty()) {
                    JSONObject ld = data.getJSONObject(data.size() - 1);
                    e.setDesc(convertTimestampToDateTime(ld.getLong("scanDate")) + ":" + ld.getString("desc"));
                }
            });
            writeExcel(response, dataList, "result.xlsx", "表名", ZopDO.class);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    @PostMapping("/getLogisticsTracks")
    public void getLogisticsTracks(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        log.info("---------物流信息查询任务开始---------");
        try {
            // 读取数据从 Excel 文件
            List<ZopDO> dataList = EasyExcel.read(file.getInputStream()).sheet().head(ZopDO.class).doReadSync();
            List<ZopDO> zops = new ArrayList<>();
            dataList.forEach(e -> {
                JSONObject result = CallFun.wayBillTrackQuery(e.getBillCode());
                Boolean status = result.getBoolean("status");
                if (status) {
                    JSONArray data = result.getJSONArray("result");
                    List<String> descs = new ArrayList<>();
                    for (int i = 0; i < data.size(); i++) {
                        JSONObject d = data.getJSONObject(i);
                        descs.add(convertTimestampToDateTime(d.getLong("scanDate")) + ":" + d.getString("desc"));
                    }
//            System.out.println(descs);
                    zops.add(new ZopDO(e.getBillCode(), String.join("\n", descs)));
                } else {
                    zops.add(new ZopDO(e.getBillCode()));
                }
            });
            log.info("---------物流信息导出excel开始---------");
            writeExcel(response, zops, "result", "物流轨迹", ZopDO.class);
            log.info("---------物流信息导出excel结束---------");
        } catch (Exception e) {
            log.error("物流信息导出异常：", e);
        }
        log.info("---------物流信息查询任务结束---------");
    }


//    @PostMapping("/getLogisticsTracks")
//    public void getLogisticsTracks(@RequestParam("file")MultipartFile file,HttpServletResponse response) throws IOException {
//        // 读取数据从 Excel 文件
//        List<ZopDO>readList=EasyExcel.read(file.getInputStream()).sheet().head(ZopDO.class).doReadSync();
//        List<ZopDO>zops=new ArrayList<>();
//        readList.forEach(e -> {
//        JSONObject result = CallFun.wayBillTrackQuery(e.getBillCode());
//        Boolean status = result.getBoolean("status");
//        if (status){
//        JSONArray data = result.getJSONArray("result");
//        for (int i = 0; i < data.size(); i++) {
//            JSONObject d = data.getJSONObject(i);
//            zops.add(new ZopDO(e.getBillCode(),convertTimestampToDateTime(d.getLong("scanDate"))+":"+d.getString("desc")));
//        }
//        }else{
//            zops.add(new ZopDO(e.getBillCode()));
//        }
//        });
//        ExportUtil.exportData(response, zops, new ZopDO());
//    }

    @PostMapping("/getAllLogisticsTracks")
    public void getAllLogisticsTracks(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        try {
            // 读取数据从 Excel 文件
            List<ZopDO> dataList = EasyExcel.read(file.getInputStream()).sheet().head(ZopDO.class).doReadSync();
            List<ZopDO> zops = new ArrayList<>();
            dataList.forEach(e -> {
//                JSONObject result = CallFun.wayBillTrackQuery(e.getBillCode());
//                Boolean status = result.getBoolean("status");
//                if (status){
//                    JSONArray data = result.getJSONArray("result");
//                    List<String>descs=new ArrayList<>();
//                    for (int i = 0; i < data.size(); i++) {
//                        JSONObject d = data.getJSONObject(i);
//                        descs.add(convertTimestampToDateTime(d.getLong("scanDate"))+":"+d.getString("desc"));
//                    }
//            System.out.println(descs);
//                    zops.add(new ZopDO(e.getBillCode(), String.join("\n", descs)));
//                }else{
//                    zops.add(new ZopDO(e.getBillCode()));
//                }
                ExpressDeliveryResult result = ExpressDeliveryUtil.queryLogistics(e.getBillCode());
                zops.add(new ZopDO(e.getBillCode(), result.getTracks().stream().map(d -> d.getScanDateStr().concat(":").concat(d.getDesc())).collect(Collectors.joining("\n"))));
            });
            writeExcel(response, zops, "result", "物流轨迹", ZopDO.class);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
}
